﻿using Global;
using IPlugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataProcessorPlugin
{
    public class DataProcessorPlugin : IPlugins.IPlugin
    {
        private IPluginHost _host;
        private Form _pluginForm;
        private Button _btnProcess;
        private TextBox _txtInput;

        public string Name { get { return "Data Processor"; } }
        public string Description { get { return "Processes data and publishes events"; } }
        public bool IsEnabled { get; set; }

        public void Initialize(IPluginHost host)
        {
            _host = host;
            // 订阅示例事件
            EventBus.Subscribe("SampleEvent", OnSampleEventReceived);
            Execute();
        }

        private void OnSampleEventReceived(object data)
        {
            if (_pluginForm != null && !_pluginForm.IsDisposed)
            {
                _pluginForm.Invoke(new Action(() =>
                {
                    var sender = data.GetType().GetProperty("Sender").GetValue(data, null);
                    var Msg = data.GetType().GetProperty("Msg").GetValue(data, null);
                    var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    _txtInput.Text += $"{now} 接收到来自{sender}的消息，消息内容为：{Msg} \r\n";
                }));
            }
        }

        public void Execute()
        {
            _pluginForm = _host.CreateSandboxForm();
            _pluginForm.Text = Name;
            _pluginForm.Size = new System.Drawing.Size(400, 300);

            _btnProcess = new Button
            {
                Text = Name,
                Dock = DockStyle.Bottom
            };
            _btnProcess.Click += (s, e) =>
            {
                var input = _txtInput.Text;
                EventBus.Publish("DataUpdated", string.Format("Processed: {0}", input.ToUpper()));
            };

            _txtInput = new TextBox
            {
                Dock = DockStyle.Fill,
                Multiline = true
            };

            _pluginForm.Controls.AddRange(new Control[] { _btnProcess, _txtInput });

            _host.MainForm.Invoke(new Action(() =>
            {
                _pluginForm.MdiParent = _host.MainForm;
                _pluginForm.Show();
            }));
        }

        public void Shutdown()
        {
            if (_pluginForm != null && !_pluginForm.IsDisposed)
            {
                _pluginForm.Invoke(new Action(() => _pluginForm.Close()));
            }

            // 取消事件订阅
            EventBus.Unsubscribe("SampleEvent", OnSampleEventReceived);
        }
    }
}
